package com.atguigu.dga.score.service.impl;

import com.atguigu.dga.score.bean.GovernanceAssessTable;
import com.atguigu.dga.score.mapper.GovernanceAssessTableMapper;
import com.atguigu.dga.score.service.GovernanceAssessTableService;
import com.atguigu.dga.score.service.GovernanceTypeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 表治理考评情况 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2023-11-02
 */
@Service
public class GovernanceAssessTableServiceImpl extends ServiceImpl<GovernanceAssessTableMapper, GovernanceAssessTable> implements GovernanceAssessTableService {

    @Autowired
    private GovernanceTypeService typeService;
    @Override
    public void generateTableScore(String assessDate) {
        //清空今天已经写入的数据
        remove(new QueryWrapper<GovernanceAssessTable>().eq("assess_date",assessDate));
        //计算分数
        List<GovernanceAssessTable> data = baseMapper.calTableScore(assessDate);
        //查询权重
        Map<String, BigDecimal> map = typeService.queryWeight();
        //为每张表的得分生成加权的分数
        calWeightScore(data,map);
        //写入
        saveBatch(data);
    }

    /**
     *
     * @param data
     * @param map  { SPEC:15
     *      STORAGE
     *      CALC
     *      QUALITY
     *      SECURITY  }
     */
    private void calWeightScore(List<GovernanceAssessTable> data, Map<String, BigDecimal> map) {

        //获取所有的权重
        Set<String> weights = map.keySet();

        data.stream()
            .forEach(t -> {
                //声明权重的分数
                BigDecimal total = BigDecimal.ZERO;
                //累加，计算权重
                for (String weight : weights) {
                    /*
                        权重名字叫什么，调用对应的 getScore权重名Avg() * 权重值
                            举例: CALC, 调用 getScoreCALCAvg()
                     */
                    try {
                        total = total.add(getWeightScoreByWeightCode(weight,t).multiply(map.get(weight)).movePointLeft(1));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
                //赋值
                t.setScoreOnTypeWeight(total);
            });
    }

    private BigDecimal getWeightScoreByWeightCode(String code,GovernanceAssessTable t) throws Exception {

        //获取方法名
        String methodName = "getScore" + code.substring(0,1) + code.toLowerCase().substring(1, code.length()) + "Avg";
        //使用反射获取到方法对象
        Method method = t.getClass().getMethod(methodName);
        //执行方法
        return  (BigDecimal)method.invoke(t);
    }
}
